package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.mapper.SetmealCheckGroupMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealCheckGroupMapper setmealCheckGroupMapper;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 新增套餐
     *
     * @param setmeal       新增的套餐
     * @param checkgroupIds 关联的检查组id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(@RequestBody Setmeal setmeal, @RequestParam Integer[] checkgroupIds) {
        try {
            // 新增套餐并返回id
            setmealMapper.insert(setmeal);
            Integer id = setmeal.getId();
            log.info("新增套餐成功, id为{}", id);
            // 添加到关系表
            // 先清空关系
            setmealCheckGroupMapper.deleteBySetmealId(id);
            if (checkgroupIds != null && checkgroupIds.length != 0) {
                log.info(Arrays.toString(checkgroupIds));
                setmealCheckGroupMapper.insert(id, checkgroupIds);
                log.info("新增套餐关系成功");
            }

            // url存入redis中
            redisTemplate.opsForSet().add("imgFromDB", setmeal.getImg());
            return true;

        }catch (Exception e){
            log.error("新增套餐失败{}", e.getMessage());
            return false;
        }
    }

    /**
     * 删除套餐
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteById(Integer id) {
        if(setmealMapper.hasNumInRelatedOrder(id) > 0){
            log.info("该套餐被订单关联，不允许删除");
            return false;
        };
        // 先查询
        Setmeal setmeal = setmealMapper.selectById(id);
        if(setmeal == null){
            log.info("不存在该套餐，不允许删除");
            return false;
        }
        // 删除套餐
        setmealMapper.deleteById(id);
        setmealCheckGroupMapper.deleteBySetmealId(id);
        log.info("删除套餐关系成功");

        // 删除redis中url
        redisTemplate.opsForSet().remove("imgFromDB", setmeal.getImg());
        return true;
    }

    /**
     * 修改套餐
     *
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @Override
    public Boolean edit(Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            // 1.先查询是否存在，保证安全性
            // 先根据id查询，没有id则根据名称查询
            Setmeal temp = null;
            if(Objects.requireNonNull(setmeal).getId() != null){
                temp = setmealMapper.selectById(setmeal.getId());
                log.info("根据id得到套餐" + temp);
            }else {
                temp = setmealMapper.selectByName(setmeal.getName()).get(0);
                log.info("根据名称得到套餐" + temp);
                setmeal.setId(temp.getId());
            }
            if(temp == null){
                log.error("不存在该套餐，不允许修改");
                return false;
            }
            // 2.得到id，根据id进行修改
            Integer id = temp.getId();
            setmealMapper.update(setmeal);
            // 3.关系表：先清空关系添加到关系表
            setmealCheckGroupMapper.deleteBySetmealId(id);
            if (checkgroupIds != null && checkgroupIds.length != 0) {
                log.info(Arrays.toString(checkgroupIds));
                setmealCheckGroupMapper.insert(id, checkgroupIds);
                log.info("修改套餐关系成功");
            }

            // 检查url是否相同，如果不同则删除redis中url并重新添加
            if(!Objects.equals(setmeal.getImg(), temp.getImg())){
                log.info("修改套餐url{}，删除redis中url{}", setmeal.getImg(), temp.getImg());
                // 删除redis中url
                try {
                    redisTemplate.opsForSet().remove("imgFromDB", temp.getImg());

                }catch (Exception e){
                    log.error("删除redis中url失败");
                }
                // 添加到redis中
                redisTemplate.opsForSet().add("imgFromDB", setmeal.getImg());
            }
            return true;
        }catch (Exception e){
            log.error("修改套餐失败{}", e.getMessage());
            return false;
        }
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealMapper.selectById(id);
    }


    /**
     * 根据套餐id查询套餐详情
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id, boolean forDetail) {
        // 首先查询套餐基本信息
        Setmeal setmeal;
        if (forDetail){
            setmeal = setmealMapper.selectDetailById(id);
            log.info("根据套餐id查询套餐详情, 套餐信息为{}", setmeal);
        }else{
            setmeal = setmealMapper.selectById(id);
            log.info("根据套餐id查询套餐基本信息{}", setmeal);
        }
        return setmeal;
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        log.info("分页查询{}", queryPageBean);
        // 判断查询条件
        if(queryPageBean.getQueryString() == null) queryPageBean.setQueryString("");
        if(queryPageBean.getCurrentPage() == null) queryPageBean.setCurrentPage(1);
        if(queryPageBean.getPageSize() == null) queryPageBean.setPageSize(10);
        // 开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> pages = (Page<Setmeal>) setmealMapper.selectByQueryString(queryPageBean.getQueryString());

        return new PageResult(pages.getTotal(), pages.getResult());
    }

    /**
     * 查询所有套餐
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return setmealMapper.selectByQueryString("");
    }

    /**
     * 上传图片
     * @param img
     * @return
     */
    @Override
    public Result upload(MultipartFile img) {
        Result result = null;
        try{
            // 原始文件名
            String originFileName = img.getOriginalFilename();
            // 获取后缀名
            String suffix = originFileName.substring(originFileName.lastIndexOf("."));
            // 构建新的文件名
            String newFilename = UUID.randomUUID().toString() + suffix;
            // 上传到阿里云OSS，返回路径名
            String url = aliOssUtil.upload(img.getBytes(), newFilename);
            log.info("文件上传成功，路径为{}", url);

            // 存储url到redis集合中
            redisTemplate.opsForSet().add("imgFromOSS", url);
            result = new Result(true, "上传成功", url);

        }catch (Exception e){
            log.error("文件上传失败");
            result = new Result(false, "上传失败");
        }
        return result;
    }

}
